<script setup lang="ts">
//boy, Cyberpunk , Top view , Face Shot (VCU) , Warm light  --style raw  --ar 3:4 --q 0.5 --v 5.2
import { ref, computed, watch, onMounted, h } from "vue";

import {
  NSelect,
  NInput,
  NUpload,
  NButton,
  NTag,
  NAvatar,
  NPopover,
  useMessage,
  NDivider,
  NRadioGroup,
  NRadioButton,
  NProgress,
  SelectRenderLabel,
  NSlider,
} from "naive-ui";
import { SvgIcon } from "@/components/common";
import { useBasicLayout } from "@/hooks/useBasicLayout";
const { isMobile } = useBasicLayout();

import axios from "@/utils/request/axios";
import closeicon from "@/assets/close.png";
const st = ref({
  text: "",
  isDisabled: false,
  isLoad: false,
  fileBase64: [],
  bot: "",
  showFace: false,
});
var loading = ref(false);
var pinyinloading = ref(false);
var reloading = ref(false);

var percentage = ref(0);
var selectedFileName = ref();
const renderLabel: SelectRenderLabel = (option) => {
  return h(
    "div",
    {
      style: {
        display: "flex",
        alignItems: "center",
      },
    },
    [
      h(
        "div",
        {
          style: {
            marginLeft: "12px",
            padding: "4px 0",
          },
        },
        [h("div", null, [option.label as string])]
      ),
      showMenu.value
        ? h(NAvatar, {
            src: closeicon,
            size: 16,
            style: {
              position: "absolute",
              background: "transparent",
              right: "40px",
              cursor: "pointer", // 添加 cursor: pointer 以表明是可点击的
            },
            onClick: () => handleDeleteClick(event, option), // 添加点击事件处理程序
          })
        : null,
    ]
  );
};
const f = ref({ sourceBase64: "", targetBase64: "" });
const songs = [
  {
    value: "语音训练",
    label: "语音训练",
  },
  {
    value: "语音合成",
    label: "语音合成",
  },
];
var haspptid = ref(false);
const msgRef = ref();
var dimensionsList = ref([]);
var ModelName = ref("");
var videoid = ref("");
var showMenu = ref(false);
var params = ref({
  ModelName: ref(null),
  FileId: ref(""),
  Pinyins: ref(""),
  Time: ref(0.1),
});
var hasmerged = ref(false);
var pinyinResult = ref({
  Pinyins: [],
  Texts: [],
});
const handleDeleteClick = (e, option) => {
  event.stopPropagation(); // 阻止事件冒泡
  console.log(option);
  del(option.label);
};
var videos = ref({
  yuyinmergevideo: "",
  finalmergevideo: "",
});
function showmenu(show: boolean) {
  showMenu.value = show;
}
var filelist = ref("");
var Speed = ref(1);
var tarinInfo = ref();
const value = ref("语音训练");
var istrain = ref(true);

const fsRef = ref();
const fsRef2 = ref();
const $emit = defineEmits(["drawSent"]);
const props = defineProps({ buttonDisabled: Boolean });

const ms = useMessage();

function del(delmodelName) {
  if (delmodelName) {
    let url = `/api/tts/delete?modelname=${delmodelName}`;
    axios
      .delete(url, {})
      .then((response) => {
        if (response.data.status == "success") {
          getData();
          ms.success("删除成功！");
        }
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
  }
}
function yuyinmerge() {
  loading.value = true;
  if (params.value.FileId) {
    let url = "/api/tts/synthesis";
    axios
      .post(url, params.value, {})
      .then((response) => {
        if (response.data.status == "success") {
          videos.value.yuyinmergevideo = response.data.data.FilePath;
          videoid.value = response.data.data.FileId;
          loading.value = false;
          $emit("drawSent", {
            type: "yuyinmergevideo",
            data: videos.value.yuyinmergevideo,
          });
          hasmerged.value = true;
          ms.success("语音合成成功！");
        }
        console.log("上传成功", response.data);
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
  }
}

function pinyinCreate() {
  pinyinloading.value = true;
  if (params.value.FileId) {
    let url = "/api/tts/checktext";
    axios
      .post(url, { FileId: params.value.FileId }, {})
      .then((response) => {
        let data = response.data.data;
        if (response.data.status == "success") {
          pinyinloading.value = false;
          params.value.Pinyins = data.Pinyins;
          pinyinResult.value.Pinyins = data.Pinyins;
          pinyinResult.value.Texts = data.Texts;
          $emit("drawSent", { type: "pinyinCreate", data: pinyinResult.value });
        }
        ms.success("生成成功！");
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
  }
}
let timer;
function yuyinTrain() {
  if (ModelName) {
    let url = "/api/tts/train";
    axios
      .post(
        url,
        {
          ModelName: ModelName.value,
          FileId: params.value.FileId,
        },
        {}
      )
      .then((response) => {
        // 轮询查询进度
        timer = window.setInterval(pollTrainInfo, 1000);
      })
      .catch((error) => {
        console.error("上传失败", error);
      });
  }
}
function pollTrainInfo() {
  console.log(params.value.ModelName);
  axios
    .get(`/api/tts/traininfo?modelname=${ModelName.value}`, {})
    .then((response) => {
      tarinInfo.value = response.data.data.TrainInfo;
      console.log(response.data.data.TrainInfo);
      if (response.data.data.TrainInfo.includes("Training")) {
        const matches = response.data.data.TrainInfo.match(
          /Training: (\d+(\.\d+)?)\s*%/
        );

        percentage.value = matches[1];
      }
      if (response.data.data.TrainInfo == "Train Finished") {
        clearInterval(timer);
      }
    })
    .catch((error) => {
      console.log(error);
    });
}
function speedCon() {
  window.speed = Speed.value;
  reloading.value = true;
  axios
    .post(
      "/api/tts/speed",
      {
        FileId: videoid.value,
        Speed: Speed.value,
      },
      {}
    )
    .then((response) => {
      if (response.data.status == "success") {
        reloading.value = false;
        //   tarinInfo.value = response.data;
        $emit("drawSent", {
          type: "yuyinmergevideo",
          data: response.data.data.FilePath,
        });
        ms.success("重新生成成功！");
      }
    })
    .catch((error) => {
      console.error("上传失败", error);
    });
}

function customRequest({ file, onSuccess, onError, onProgress }) {
  const uploadUrl = "/api/upload/file";

  const formData = new FormData();
  formData.append("file", file.file);

  axios
    .post(uploadUrl, formData, {})
    .then((response) => {
      if (response.data.status == "success") {
        console.log(response.data.data);
        params.value.FileId = response.data.data.FileId;
        // 处理上传成功逻辑
        ms.success("上传成功！");
      }
    })
    .catch((error) => {
      console.log(error);

      // 处理上传失败逻辑
      onError(error);
    });
}
function customRequesthe({ file, onSuccess, onError, onProgress }) {
  const uploadUrl = "/api/upload/file";

  const formData = new FormData();
  formData.append("file", file.file);

  axios
    .post(uploadUrl, formData, {})
    .then((response) => {
      if (response.data.status == "success") {
        //   console.log(response.data.data);
        params.value.FileId = response.data.data.FileId;
        haspptid.value = true;
        window.pptFileId = response.data.data.FileId;
        ms.success("上传成功！");
      }
      // 处理上传成功逻辑
    })
    .catch((error) => {
      console.log(error);

      // 处理上传失败逻辑
      onError(error);
    });
}
const tabmenu = (e) => {
  istrain.value = e.target._value == "语音合成" ? false : true;
  if (e.target._value == "语音合成") {
    getData();
  } else {
    dimensionsList.value = [];
  }
  console.log(e.target._value);
};
function getData() {
  // 获取语言模型
  let url = "/api/tts/models";
  axios
    .get(url, {})
    .then((res) => {
      if (res.data.status == "success") {
        console.log(res.data.data);

        dimensionsList.value = [];
        res.data.data.ModelNames.forEach((element) => {
          let obj = {
              label: element,
              value: element,
          };
          dimensionsList.value.push(obj);
        });


        // res.data.data.ModelNames.forEach((element) => {
        //   const exists = dimensionsList.value.some(
        //     (item) => item.label === element || item.value === element
        //   );

        //   if (!exists) {
        //     let obj = {
        //       label: element,
        //       value: element,
        //     };
        //     dimensionsList.value.push(obj);
        //   }
        // });
      }
    })
    .catch((error) => {
      console.error("上传失败", error);
    });
}

//const config=
</script>
<template>
  <div class="overflow-y-auto bg-[#fafbfc] px-4 dark:bg-[#18181c] h-full">
    <!-- 语音分类按钮 -->
    <section class="mb-4">
      <n-radio-group v-model:value="value" name="radiobuttongroup1">
        <n-radio-button
          v-for="song in songs"
          :key="song.value"
          :value="song.value"
          :label="song.label"
          @change="tabmenu"
        />
      </n-radio-group>
    </section>
    <!-- 语音训练内容 -->
    <div v-if="istrain">
      <div class="flex">
        <n-upload
          accept=".zip"
          action=" https://f166-2001-250-3c0f-1008-00-811e.ngrok-free.app/api/upload/file"
          :custom-request="customRequest"
        >
          <n-button>上传ZIP文件</n-button>
        </n-upload>
      </div>
      <div class="mb-1 flex items-center" style="margin-top: 20px">
        <span> 语音模型： </span>
        <div class="w-[190px]">
          <n-input
            type="text"
            v-model:value="ModelName"
            placeholder="请输入训练模型的名称"
            clearable
          />
        </div>
      </div>
      <div class="mb-" style="margin-top: 20px">
        <span> 训练进度： </span>
        <!-- 显示进度 -->
        <span v-if="typeof tarinInfo == 'string'"> {{ tarinInfo }} </span>

        <n-progress
          type="line"
          :percentage="percentage"
          :indicator-placement="'inside'"
          processing
          style="margin-bottom: 20px"
        />
      </div>
      <div class="mb-4 flex justify-between items-center">
        <div class="flex">
          <n-button
            type="primary"
            :block="true"
            @click="yuyinTrain()"
            :disabled="!(params.FileId && ModelName)"
          >
            <SvgIcon icon="mingcute:send-plane-fill" />

            <template v-if="st.isLoad"> 翻译中...</template>
            <template v-else> 开始语音训练</template>
          </n-button>
        </div>
      </div>
    </div>
    <!-- 语音合成内容 -->
    <div v-else>
      <div class="flex">
        <n-upload
          :custom-request="customRequesthe"
          accept=".pptx"
          action=" https://f166-2001-250-3c0f-1008-00-811e.ngrok-free.app/api/upload/file"
        >
          <n-button>上传PPT文件</n-button>
        </n-upload>
      </div>
      <!-- <div class="mb-1 flex" style="margin-top: 20px">
        <span style="width: 70px"> ppt备注： </span>
        <div class="w-[190px]">
          <n-input
            type="text"
            v-model:value="f.prompt"
            placeholder="ppt备注"
            disabled
            clearable
          />
        </div>
      </div> -->
      <div class="mb-1 flex items-center" style="margin-top: 20px">
        <span style="width: 90px; text-align: end"> 语音模型： </span>
        <div class="w-[190px]">
          <n-select
            v-model:value="params.ModelName"
            placeholder="请选择语音模型"
            :options="dimensionsList"
            :on-update:show="showmenu"
            :render-label="renderLabel"
            size="small"
            :clearable="true"
          >
            <span>111</span>
          </n-select>
        </div>
      </div>

      <div class="mb-1 flex items-center" style="margin-top: 20px">
        <span style="width: 90px; text-align: end"> 句间间隔时间: </span>
        <div class="w-[190px]">
          <n-slider v-model:value="params.Time" max="3" :step="0.1" />
        </div>
      </div>

      <div class="mb-4">
        <div class="flex" style="margin-bottom: 10px">
          <n-button
            type="primary"
            :block="true"
            :loading="pinyinloading"
            :disabled="
              !(params.FileId && params.ModelName && haspptid) || pinyinloading
            "
            @click="pinyinCreate()"
          >
            <SvgIcon icon="mingcute:send-plane-fill" />

            <template v-if="st.isLoad"> 翻译中...</template>
            <template v-else> 生成拼音</template>
          </n-button>
        </div>
        <div class="flex">
          <n-button
            type="primary"
            :block="true"
            :loading="loading"
            @click="yuyinmerge()"
            :disabled="!params.Pinyins || loading"
          >
            <SvgIcon icon="mingcute:send-plane-fill" />

            <template v-if="st.isLoad"> 翻译中...</template>
            <template v-else> 开始语音合成</template>
          </n-button>
        </div>
      </div>
      <div class="mb-1 flex items-center" style="margin-top: 20px">
        <span style="width: 70px; text-align: end"> 语速： </span>
        <div class="w-[190px]">
          <n-slider
            v-model:value="Speed"
            max="2"
            :step="0.05"
            :disabled="!hasmerged"
          />
        </div>
        <div>
          <n-button
            type="primary"
            :block="true"
            :loading="reloading"
            @click="speedCon()"
            :disabled="!hasmerged || reloading"
          >
            <template v-if="st.isLoad"> 生成中...</template>
            <template v-else> 重新生成</template>
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>
<style>
.aspect-item.active,
.aspect-item.active .aspect-box {
  border-color: #86dfba;
}
</style>